package com.common.utils;

import java.lang.reflect.Method;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

//import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.aop.MethodBeforeAdvice;

import com.system.domain.T_operation_log;
import com.system.mapper.T_operation_logMapper;

public class LogBefore implements MethodBeforeAdvice {

	private static final Logger logger = Logger.getLogger(LogBefore.class);

	@Resource
	private T_operation_logMapper mapper;

	public void before(Method method, Object[] args, Object target) {
		//throws Throwable {
		String starttime = DateUtil.getCurrDateTime();

		try{
			String username = "";
			StringBuffer sb = new StringBuffer();
			for (int i=0; i<args.length;i++) {
				sb.append(i + "=" + args[i].toString()+ "; ");
				//			if (null == args[i]) {
				//				continue;
				//			}
				if (args[i] instanceof HttpServletRequest) {
					HttpServletRequest request = (HttpServletRequest) args[i];
					//curUser = (T_user_detail) request.getSession().getAttribute("FREE_CURRENT_USER");
					username = (String) request.getSession().getAttribute("FREE_CURRENT_USER");
				    //logger.error("------用户session名字="+username);
				}
			}
			if (null == username||"".equals(username)) {
				logger.error("------操作日志&&&&&&方法执行前Start：-》用户未登录或者直接跳转（请求方法中没传递httprequest），获取不到用户session操作信息------");
				username = "用户未登录或者直接跳转";
			} else {
				logger.error("------操作日志&&&&&&方法执行前Start：-》获取到当前操作用户为:" + username+"------");
			}
			logger.error("------操作日志&&&&&&方法执行前：-》获取到当前用户操作业务类名字:" + target.getClass().getName() + ";操作方法名字:" + method.getName()+"------");
			logger.error("------操作日志&&&&&&方法执行前End：获取到当前用户操作业务参数值-》:" + sb.toString() +"------");

			//记录跟踪审计信息
			T_operation_log operlog = new T_operation_log();
			operlog.setUserid(username);
			operlog.setOperation_start_tm(starttime);
			operlog.setUrl("访问类名："+target.getClass().getName()+",方法名:"+method.getName());
			operlog.setArgs(sb.toString());
			operlog.setSession_id(Thread.currentThread().getId()+"");
			operlog.setSystemid("SH");
			//查询访问T_operation_log时，不做日志数据库记录，只做日志文件记录
			if(!target.getClass().getName().contains("T_operation_log")){
				mapper.save(operlog);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e);
		}
	}
}
